** Merge QWI with MW 
** JHL

*************************************
** Set up workspace
*************************************
version 14.0
clear all
set more off

cd "${path_home}"
adopath + ../programs

** log using "${path_log}/c05_merge_qwi_mw", text replace

*************************************
** Start work here
*************************************
timer on 1

*************************************
** [1] Append processed files
*************************************

** Run only once, do not run when parallel, need to wait until all files are created 
local states "ak al ar az ca co ct dc de fl ga hi ia id il in ks ky la ma md me mi mn mo ms mt nc nd ne nh nj nm nv ny oh ok or pa ri sc sd tn tx ut va vt wa wi wv wy "

tokenize "`states'"

foreach i of numlist 1/51 {
	append using "${path_big_dta}/qwi/latest/qwi_``i''_sa_f_gc_n4_op_u_ns"
	** erase qwi_``i''_sa_f_gc_n4_op_u_ns.dta 
}

save "${path_big_dta}/qwi/latest/qwi_all_sa_f_gc_n4_op_u_ns", replace

*************************************
** [2] Add in MW
*************************************

use "${path_big_dta}/qwi/latest/qwi_all_sa_f_gc_n4_op_u_ns", clear 

* Drop state level observations
drop if geography<100
gen state=(geography-mod(geography,1000))/1000
gen county=mod(geography,1000)

gen fips_state_code = state
gen fips_county_code = county

keep if year>=2006&year<=2015

gen yq=yq(year,quarter)
format yq %tq
gen statefips = state
gen quarterly_date = yq 

merge m:1 statefips quarterly_date using "${path_big_dta}/mw/VZ/VZ_state_stata/VZ_state_quarterly", keep(match) nogen

keep if agegrp=="A00"&sex==0

** Merge with state MW, fl 
merge m:1 statefips quarterly_date using "${path_big_dta}/mw/VZ/VZ_state_stata/VZ_state_quarterly_fl.dta", keep(match match_update match_conflict) nogen update 
cap noi gen log_mwq=log(mean_mw)

** Gen var
cap drop panelvar
egen panelvar=group(industry geography)
cap gen state=fips_state_code
	
** Merge with county population 
merge m:1 fips_state_code fips_county_code year using "${path_big_dta}/us_counties/county_pop_0015", keep(master match) nogen

gen logpop=log(popestimate)

** Generate y variables (log)
cap noi gen log_earnb=log(earnbeg)
cap noi gen log_emp=log(empend)

** Merge in indicators on poor counties 
merge m:1 fips_state_code fips_county_code using "${path_big_dta}/qcew/qcew_county_wage_q24_0415", keep(master match) nogen keepus(kaitz_y2006_qtr1_q2_c)

save "${path_big_dta}/qwi/qwi_all_sa_f_gc_n4_op_u_ns_mw_0615", replace

*************************************
** Close workspace
*************************************
timer off 1
timer list 1
** log close